package de.koller.worlders.engine.entity.mo.topdown;

import de.koller.oceanFramework.math.Vec;
import de.koller.oceanFramework.tree.Mother;
import de.koller.worlders.WSea;
import de.koller.worlders.engine.WInputGL;
import org.lwjgl.input.Keyboard;

public class TDPlayerSteer extends WSea {

	@Mother private TopDownPlayer tdp;

	@Override
	protected void init() {
		super.init();
		
		wroot.getEntityContainer().setShowCrosshair( true );
	}
	
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		if( tdp.isDeath() )
			return;
		
		if( wroot.getDebug().isActive() || wroot.getGui().getConsoleInput().isOpen() )
			return;
		
		wroot.getInput().setMouseGrab( true );
		rotate();
		reseting();
		walking();
	}
	
	private void rotate() {
		WInputGL in = wroot.getInput();
		
		int dr = in.getMouseDX();
		float r = tdp.getDirection() - (dr * 0.002f);
		r %= Math.PI * 2f;
		tdp.setDirection( r );
		
		int dy = in.getMouseDY();
		float ry = tdp.getCrosshairdis() - dy * 0.02f;
		tdp.setCrosshairdis( ry );
	}
	
	private void walking() {
		WInputGL in = wroot.getInput();
		
		int a = 0;
		a += ( in.isKeyDown( Keyboard.KEY_D ) || in.isKeyDown( Keyboard.KEY_RIGHT ) ) ?  1 : 0;
		a += ( in.isKeyDown( Keyboard.KEY_A ) || in.isKeyDown( Keyboard.KEY_LEFT  ) ) ? -1 : 0;
		
		int b = 0;
		b += ( in.isKeyDown( Keyboard.KEY_S ) || in.isKeyDown( Keyboard.KEY_DOWN ) ) ? 1 : 0;
		b += ( in.isKeyDown( Keyboard.KEY_W ) || in.isKeyDown( Keyboard.KEY_UP  ) ) ? -1 : 0;
		
		if( a == 0 && b == 0 ) {
			tdp.walk( 0, 0 );
			return;
		}
		
		Vec r = new Vec( a, b );
		r.setLength( 1 );
		r.deltaDirection( -tdp.getDirection() );
		
		tdp.walk( r.getXf(), r.getYf() );
	}
	
	private void reseting() {
		WInputGL in = wroot.getInput();
		
		if( !in.isKeyPressed( Keyboard.KEY_R ) )
			return;
		
		tdp.reset();
	}
	
}
